package com.aidex.wxCompany;

import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class WxWrokDomainService {


    @Autowired
    private RedisCache redisCache;

    public static void main(String[] args) {
        // String robot = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ad790f2d-a464-4c74-a1e1-eef53a4b3bf0";

        String robot = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=026264e3-112c-48a1-80c3-54d56e8323ac";
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "text");
        Map<String, Object> contests = new HashMap<>();
        String text = "-----新客户进线-----\n" +
                "客户姓名:熊老湿 \n" +
                "电话:177***4470  ";
        contests.put("content", text);
        String mentionedList[] = null;
        if (mentionedList != null) {
            contests.put("mentioned_list", Arrays.asList(mentionedList)); // 确保这些是有效的用户ID
        }
        String mobileList[] = {"17771704470"};
        if (mobileList != null) {
            contests.put("mentioned_mobile_list", Arrays.asList(mobileList));
        }
        message.put("text", contests);

        String corpId = "wwef2529d371419b3a";
        String corpSecret = "4BYelkhf-gFOz5X_pfZqlYzwj9vBPSuEKSORt5oqGLA";
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpSecret}";
        Map<String, Object> res = new RestTemplate().getForObject(url, Map.class, corpId, corpSecret);
        String accessToken = (String) res.get("access_token");
        Long expiresTime = System.currentTimeMillis() + ((Integer) res.get("expires_in") - 300) * 1000L;

        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(robot, message, Map.class, accessToken);

        System.out.println("Response: " + response);

        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }

    // 获取AccessToken（带缓存）
    public String getAccessToken() {
        String corpId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpId").getConfigValue();
        String corpSecret = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpSecret").getConfigValue();
        String accessToken = redisCache.getCacheObject("wxwork:accessToken");
        if (StringUtils.isEmpty(accessToken)) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpSecret}";
            Map<String, Object> response = new RestTemplate().getForObject(url, Map.class, corpId, corpSecret);
            accessToken = (String) response.get("access_token");
            Long expiresTime = System.currentTimeMillis() + ((Integer) response.get("expires_in") - 300) * 1000L;
            redisCache.setCacheObject("wxwork:accessToken", accessToken, expiresTime.intValue(),
                    TimeUnit.SECONDS);
        }
        return accessToken;
    }

    /**
     * 该接口用于获取配置过客户群管理的客户群列表。
     *
     * @return
     */
    public String getChatIdFromGroupChat() {
        String accessToken = getAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=" + accessToken;
        // 构造请求体
        String requestBody = String.format(
                "{\"status_filter\":0,\"limit\":10}"
        );
        // 设置Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, request, String.class);
        System.out.println("Response: " + response);

        return response;
    }

    public void createGroupChat(String name, String owner) {
        String accessToken = getAccessToken();
        System.out.println(accessToken);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token=" + accessToken;
        // 构造请求体
        // 使用Map构建请求体（更安全）
        Map<String, Object> message = new HashMap<>();
        message.put("name", name);
        message.put("owner", owner);
        message.put("userlist", Arrays.asList("Lidong", "Xiongxing", "Zhouzhong")); // 确保这些是有效的用户ID

        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(url, message, Map.class, getAccessToken());

        System.out.println("Response: " + response);

        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }

    /**
     * 发送群消息
     *
     * @param chatId  wrhjJVKwAA0O7CQJ76aEBF24dF0Yl0BA
     * @param message
     */
    public void sendMessageToChat(String chatId, String message) {
        String accessToken = getAccessToken();
        System.out.println(accessToken);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + accessToken;
        // 构造请求体
        String requestBody = String.format(
                "{\"chatid\":\"%s\",\"msgtype\":\"text\",\"text\":{\"content\":\"%s\"},\"sage\":0}",
                chatId, message
        );

        // 设置Header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, request, String.class);
        System.out.println("Response: " + response);
    }

    /**
     * 使用机器人给群成员发送消息
     *
     * @param content
     * @param robot
     */
    public void sendTxtMessageFromRobotToGroup(String robot, String content, String[] mentionedList,
                                               String[] mobileList) {

        // 使用Map构建请求体（更安全）
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "text");
        Map<String, Object> contests = new HashMap<>();
        contests.put("content", content);
        if (mentionedList != null) {
            contests.put("mentioned_list", Arrays.asList(mentionedList)); // 确保这些是有效的用户ID
        }
        if (mobileList != null) {
            contests.put("mentioned_mobile_list", Arrays.asList(mobileList));
        }
        message.put("text", contests);


        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(robot, message, Map.class, getAccessToken());

        System.out.println("Response: " + response);

        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                throw new RuntimeException("发送失败: " + body.get("errmsg"));
            }
        } else {
            throw new RuntimeException("请求失败: " + response.getStatusCode());
        }
    }
}
